package com.kingtone.rongji.tool;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.text.TextUtils;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.kingtone.rongji.HuoDongActivity;
import com.kingtone.rongji.MainActivity;
import com.kingtone.rongji.ProductDetailActivity;
import com.kingtone.rongji.biz.Address;
import com.kingtone.rongji.biz.HomeImage;
import com.kingtone.rongji.ui.LoadingProgress;

public class RongJiUtils {
	
	private static LoadingProgress progressDialog;
	
	// 主页面图片地址处理
	public static void handleHomeImageUrl(HomeImage item) {
		if(null != item && !TextUtils.isEmpty(item.getImageUrl())) {
			item.setImageUrl(AppRestClient.BASE_HOME_IMG_URL + item.getImageUrl().substring(0, 6) + "/" + item.getImageUrl());
		}
	}
	
	// 主页面跳转Action类型
	public static final int ACTION_PRODACTION = 0;// 产品详情
	public static final int ACTION_SEARCH     = 1;// 搜索
	public static final int ACTION_TOPIC      = 2;// 专题
	public static final int ACTION_WEXIN      = 3;// 微信
	public static final int ACTION_CATEGORY   = 4;// 分类
	public static final int ACTION_OPEN_WEXIN = 5;// 微信打开
	public static final int ACTION_ADV        = 6;// 
	
	//http://m.rongji365.com/Product/SummerAdv
	private static final String ACTION_PRODACTION_STR = "product/productdetail?prd=";// 产品详情
	private static final String ACTION_SEARCH_STR     = "product/productlist?keyword=";// 搜索
	private static final String ACTION_TOPIC_STR      = "storage/staticresource/";// 专题
	private static final String ACTION_WEXIN_STR      = "mp.weixin.qq.com";// 微信
	private static final String ACTION_CATEGORY_STR   = "product/productlist?sid=";// 分类
	private static final String ACTION_OPEN_WEXIN_STR = "m.rongji365.com/weixinportal";// 微信打开
	private static final String ACTION_ADV_STR        = "product/summeradv";//
	
	public static final String FOLDER_SHARE_IMAGES   = "/sdcard/rongji/shared_images/";// 微信
	
	// 获取主页面跳转Action类型
	public static int getActionType(HomeImage item) {
		if(null != item && !TextUtils.isEmpty(item.getNavigateUrl())) {// 产品详情
			if(item.getNavigateUrl().toLowerCase(Locale.US).indexOf(ACTION_PRODACTION_STR)>0) {
				return ACTION_PRODACTION;
			} else if(item.getNavigateUrl().toLowerCase(Locale.US).indexOf(ACTION_SEARCH_STR)>0) {// 搜索
				return ACTION_SEARCH;
			} else if(item.getNavigateUrl().toLowerCase(Locale.US).indexOf(ACTION_TOPIC_STR)>0) {// 专题
				return ACTION_TOPIC;
			} else if(item.getNavigateUrl().toLowerCase(Locale.US).indexOf(ACTION_WEXIN_STR)>0) {// 微信
				return ACTION_WEXIN;
			} else if(item.getNavigateUrl().toLowerCase(Locale.US).indexOf(ACTION_CATEGORY_STR)>0) {// 微信
				return ACTION_CATEGORY;
			} else if(item.getNavigateUrl().toLowerCase(Locale.US).indexOf(ACTION_OPEN_WEXIN_STR)>0) {// 微信
				return ACTION_OPEN_WEXIN;
			} else if(item.getNavigateUrl().toLowerCase(Locale.US).indexOf(ACTION_ADV_STR)>0) {// 微信
				return ACTION_ADV;
			}
		}
		return ACTION_PRODACTION;
	}
	
	// 获取分类id
	public static String getCategoryIdFromHomeImage(HomeImage item) {
		if(null != item && !TextUtils.isEmpty(item.getNavigateUrl())) {
			String url = item.getNavigateUrl();
			int index = url.toLowerCase(Locale.US).indexOf(ACTION_CATEGORY_STR);
			if(index>0) {
				String temp = url.substring(index + ACTION_CATEGORY_STR.length());
				int end = temp.indexOf("&");
				if(end > 0)
				{
					return temp.substring(0, end);
				}
				return temp;
			}
		}
		return "";
	}
	
	// 获取产品id
	public static String getProductIdFromHomeImage(HomeImage item) {
		if(null != item && !TextUtils.isEmpty(item.getNavigateUrl())) {
			String url = item.getNavigateUrl();
			int index = url.toLowerCase(Locale.US).indexOf(ACTION_PRODACTION_STR);
			if(index>0) {
				String temp = url.substring(index + ACTION_PRODACTION_STR.length());
				int end = temp.indexOf("&");
				if(end > 0)
				{
					return temp.substring(0, end);
				}
				return temp;
			}
		}
		return "";
	}
	
	// 获取搜索关键字
	public static String getSearchKeyFromHomeImage(HomeImage item) {
		if(null != item && !TextUtils.isEmpty(item.getNavigateUrl())) {
			String url = item.getNavigateUrl();
			int index = url.toLowerCase(Locale.US).indexOf(ACTION_SEARCH_STR);
			if(index>0) {
				String temp = url.substring(index + ACTION_SEARCH_STR.length());
				int end = temp.indexOf("&");
				if(end > 0)
				{
					try {
						return URLDecoder.decode(temp.substring(0, end), "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				try {
					return URLDecoder.decode(temp, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}
	
	// 跳转产品详情页面
	public static void goProductDetail(Activity activity, String pid) {
		if(null != activity && !TextUtils.isEmpty(pid)) {
			Intent intent = new Intent(activity, ProductDetailActivity.class);
			intent.putExtra("productId", pid);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			activity.startActivity(intent);
		}
	}
	
	// 跳转搜索页面
	public static void goSearch(Activity activity, int sid) {
		if(null != activity) {
			MainActivity main = (MainActivity) activity;
			main.onQueryChanged(sid, "", false);
		}
	}
	
	// 跳转搜索页面
	public static void goSearch(Activity activity, String key) {
		if(null != activity && !TextUtils.isEmpty(key)) {
			MainActivity main = (MainActivity) activity;
			main.onQueryChanged(0, key, false);
		}
	}
	
	// 跳转到微信
	public static void goHuodong(Activity activity, String url) {
		if(null != activity && !TextUtils.isEmpty(url)) {
			Intent intent = new Intent(activity, HuoDongActivity.class);
			intent.putExtra("url", url);
			activity.startActivity(intent);
		}
	}
	
	public static void showEmptyProgress(Context paramContext) {
		try {
			if (progressDialog == null) {
				progressDialog = new LoadingProgress(paramContext);
				progressDialog.setCancelable(false);
				progressDialog.setIndeterminate(false);
			}
			progressDialog.show();
			return;
		} catch (Exception localException) {
			localException.printStackTrace();
		}
	}

	public static void dismissProgress() {
		try {
			if (progressDialog != null) {
				progressDialog.dismiss();
				progressDialog = null;
			}
			return;
		} catch (Exception localException) {
			localException.printStackTrace();
		}
	}
	
	/**
	 * 将服务器传回来的/Date(1359127022467+0800)\数据格式转化为年月日时分秒格式
	 * @param str
	 * @return
	 */
	public static String revertDate(String str)
	{
		final String time = str.substring(6,str.length()-7);
	     
	    Date date = new Date(Long.parseLong(time));
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	    return format.format(date);
	}
	
	/**
	 * 获取当前时间的上个月
	 * @return
	 */
	public static String getLastMonthDate()
	{
		 Calendar c = Calendar.getInstance();  
	     c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));  
	     c.setTime(new Date());
         c.add(Calendar.MONTH, -1);

	     Date lasMonth = c.getTime();
	     long time = lasMonth.getTime();
	     return "/Date(" + time + "+0800)/";
	}
	
	/**
	 * 获取当前时间的下一天
	 * @return
	 */
	public static String getNextDayDate()
	{
		 Calendar c = Calendar.getInstance();  
	     c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));  
	     c.setTime(new Date());
         c.add(Calendar.DAY_OF_MONTH, 1);

         Date nextDay = c.getTime();
	     long time = nextDay.getTime();
	     return "/Date(" + time + "+0800)/";
	}
	
	public static String formatCost(double item) {
		DecimalFormat df = new DecimalFormat("0.00");
		return df.format(item);
	}
	
	/**
	 待确认 = 0
	 待支付 = 1
	  已审核 = 2
	  已付款 = 3(在线付款)
	  待出库 = 4
	  已出库 = 5
	  已发货（等待收货） = 6
	  已签收 = 7 
	  已收款（货到付款） = 8
	  已结束 = 9
	  用户手动取消 = 13
	  系统自动作废 = 14
	  客服手动取消 = 15
	 */
	
	public static String getOrderStatusStr(int status)
	{
		String orderStatus = "待确认";
		switch(status)
		{
		case 0:
			orderStatus =  "待确认";
			break;
		case 1:
			orderStatus =  "待支付";
			break;
		case 2:
			orderStatus =  "已审核";
			break;
		case 3:
			orderStatus =  "已付款";
			break;
		case 4:
			orderStatus =  "待出库";
			break;
		case 5:
			orderStatus =  "已出库 ";
			break;
		case 6:
			orderStatus =  "已发货";
			break;
		case 7:
			orderStatus =  "已签收";
			break;
		case 8:
			orderStatus =  "已收款";
			break;
		case 9:
			orderStatus =  "已结束";
			break;
		case 13:
			orderStatus =  "用户手动取消";
			break;
		case 14:
			orderStatus =  "系统自动作废";
			break;
		case 15:
			orderStatus =  "客服手动取消";
			break;	
		}
		
		return orderStatus;
	}
	
	/**
	 * 根据经纬度获取距离
	 * @param latA
	 * @param lngA
	 * @param latB
	 * @param lngB
	 * @return
	 */
	public static String getDistance(double latA, double lngA, double latB, double lngB, Address add)
	{
		LatLng p1 = null;
   	    if(latA == 0 || lngA == 0)
   	    {
   	    	if(add != null)
   	    	{
   	    		p1 = new LatLng(add.getLatitude(), add.getLongitude());
   	    	}
   	    	
   	    }else
   	    {
   	    	p1 = new LatLng(latA, lngA);
   	    }
   	    LatLng p2 = new LatLng(latB, lngB);
		DecimalFormat df  = new DecimalFormat("######0.00"); 
		return df.format(DistanceUtil.getDistance(p1, p2) / 1000);
	}
	
	
	/**
	 * 启动定位Service
	 * @param paramContext
	 */
	public static void startLocation(Context paramContext)
	{
	    Intent localIntent = new Intent(paramContext, LocationService.class);
	    paramContext.startService(localIntent);
	}
	
	public static String storeInSD(Bitmap bitmap, String imageName) {
        File file = new File(FOLDER_SHARE_IMAGES);
        if (!file.exists()) {
            file.mkdirs();
        }
        File imgFile = new File(file, imageName);
        if(!imgFile.exists())
        {
	        try {
	        	imgFile.createNewFile();
	            FileOutputStream fos = new FileOutputStream(imgFile);
	            bitmap.compress(CompressFormat.JPEG, 100, fos);
	            fos.flush();
	            fos.close();
	        } catch (FileNotFoundException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
        }
        return imgFile.getPath();
    }
}
